
package com.netease.xone.fragment;

import protocol.XoneCallBack;
import protocol.XoneService;
import protocol.XoneServiceCode;
import protocol.meta.AppInfo;
import protocol.meta.Source;
import protocol.transactions.TransactionGetSourceInfoList;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.X1LoadingAdapterViewBase.OnLoadingListener;
import com.netease.image.ImageType;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityInfoDetail;
import com.netease.xone.adapter.AdapterInfo;
import com.netease.xone.widget.LoadingImageView;
import com.netease.xone.widget.listview.LoadingListView;

import db.XoneDBTables.AppInfoTable;
import db.manager.ManagerAccount;
import db.manager.ManagerAppInfo;

public class FragmentSourceDetail extends FragmentBase implements LoaderCallbacks<Cursor> {

    public static FragmentSourceDetail newInstance(int sourceId, String sourceName) {
        FragmentSourceDetail f = new FragmentSourceDetail();
        Bundle b = new Bundle();
        b.putInt(XoneConsts.BUNDLE_KEY.SOURCE_ID, sourceId);
        b.putString(XoneConsts.BUNDLE_KEY.SOURCE_NAME, sourceName);
        f.setArguments(b);
        return f;
    }

    private int mSourceId;
    private String mSourceName;
    private Source mSource;
    private long mMaxTime;
    // Tid
    private int mSourceTid;
    private int mSubscribeTid;
    private int mSourceInfoTid;
    private int mHeadSourceInfoTid;
    // Views
    private LoadingListView mLoadingList;// 总体listview
    // 头图部分
    private LoadingImageView mHeadImage;
    private TextView mNameText;// 主题名
    private TextView mDescText;// 描述
    private TextView mSubscribeCountText;
    private TextView mSubscribeButton;
    private LoadingImageView mSourceAvatar;
    // 讨论部分
    private AdapterInfo mAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mSourceId = getArguments().getInt(XoneConsts.BUNDLE_KEY.SOURCE_ID, -1);
        mSourceName = getArguments().getString(XoneConsts.BUNDLE_KEY.SOURCE_NAME);
        getActivity().setTitle(R.string.pgsource_title);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mLoadingList = (LoadingListView)View.inflate(getActivity(), R.layout.view_loading_listview,
                null);
        mLoadingList.disablePullToRefresh();
        mLoadingList.setOnItemClickListener(mItemClick);
        mLoadingList.setOnLoadingListener(new OnLoadingListener() {

            @Override
            public void onRefreshing() {

            }

            @Override
            public void onLoading() {
                mSourceTid = XoneService.getInstance().doGetSourceDetail(mSourceId);
                // 取得头条资讯
                mHeadSourceInfoTid = XoneService.getInstance().doGetSourceInfoList(
                        String.valueOf(mSourceId), TransactionGetSourceInfoList.TYPE_HEAD, -1, -1);
            }

            @Override
            public void onLoadingMore() {
                mSourceInfoTid = XoneService.getInstance().doGetSourceInfoList(
                        String.valueOf(mSourceId), TransactionGetSourceInfoList.TYPE_COMMON,
                        XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT, mMaxTime);
            }
        });
        // 头图
        View head = View.inflate(getActivity(), R.layout.view_source_detail_banner, null);
        mSourceAvatar = (LoadingImageView)head.findViewById(R.id.source_avatar);
        if (mSourceAvatar != null) {
            int size = getResources().getDimensionPixelSize(R.dimen.common_avatar_size);
            mSourceAvatar.setServerClipSize(size, size);
        }
        mHeadImage = (LoadingImageView)head.findViewById(R.id.source_head_image);
        int width = getActivity().getResources().getDisplayMetrics().widthPixels;
        mHeadImage.setServerClipSize(width, 0);// 设置服务器裁剪大小
        mNameText = (TextView)head.findViewById(R.id.source_name);
        mNameText.setText(mSourceName);
        mDescText = (TextView)head.findViewById(R.id.source_desc);
        mSubscribeCountText = (TextView)head.findViewById(R.id.source_subscribe_count);
        mSubscribeCountText.setText(getString(R.string.people_has_subscribed, 0));
        mSubscribeButton = (TextView)head.findViewById(R.id.source_subscribe_button);
        mSubscribeButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (mSource != null && mSource.isSubscribed) {
                    mSubscribeTid = XoneService.getInstance().doUnsubscribe(mSourceId);
                } else {
                    mSubscribeTid = XoneService.getInstance().doSubscribe(-1, mSourceId);
                }
            }
        });

        // add views
        mLoadingList.getRefreshableView().addHeaderView(head);
        mAdapter = new AdapterInfo(getActivity(), null);
        mLoadingList.setAdapter(mAdapter);
        XoneService.getInstance().addListener(mCallBack);
        return mLoadingList;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // initLoader(int id, Bundle args, LoaderCallbacks<D> callback)
        getLoaderManager().initLoader(0, null, this);
        mLoadingList.load();
    }

    @Override
    public void onDestroy() {
        XoneService.getInstance().removeListener(mCallBack);
        super.onDestroy();
    }

    private OnItemClickListener mItemClick = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String infoId = null;
            Object obj = parent.getAdapter().getItem(position);
            if (obj instanceof AppInfo) {
                infoId = ((AppInfo)obj).getInfoId();
                if (TextUtils.isEmpty(infoId)) {
                    return;
                }
            }
            ActivityInfoDetail.startActivity(getActivity().getApplicationContext(), infoId,
                    ActivityInfoDetail.MODE_FROM_INFO);
        }
    };

    private XoneCallBack mCallBack = new XoneCallBack() {

        @Override
        public void onGetSourceDetail(int transactionId, Source source) {
            if (mSourceTid == transactionId && source != null) {
                mSource = source;
                if (!TextUtils.isEmpty(source.avatar)) {
                    int roundSize = getResources().getDimensionPixelSize(
                            R.dimen.common_avatar_rounder);
                    mSourceAvatar.setImageResource(R.drawable.avatar_source_default_round);
                    mSourceAvatar
                            .setLoadingImage(source.avatar, ImageType.RoundMemCache, roundSize);
                }
                mSourceName = source.sourceName;
                mNameText.setText(mSourceName);
                mHeadImage.setLoadingImage(source.headImageUrl);
                mDescText.setText(source.desc);
                mSubscribeCountText.setText(getString(R.string.people_has_subscribed,
                        source.subscribeCount));
                if (source.isSubscribed) {
                    // 已订阅的状态
                    mSubscribeButton.setTextColor(getResources().getColor(R.color.button_gray));
                    mSubscribeButton.setText(R.string.cancel_subscribe);
                    mSubscribeButton.setBackgroundResource(R.drawable.selector_gray_btn);
                } else {
                    // 未订阅状态
                    mSubscribeButton.setTextColor(Color.WHITE);
                    mSubscribeButton.setText(R.string.subscribe);
                    mSubscribeButton.setBackgroundResource(R.drawable.selector_blue_btn);
                }
            }
        };

        @Override
        public void onSubscribe(int transactionId, int[] subjectIdAndSourceId) {
            if (mSubscribeTid == transactionId) {
                int sourceId = subjectIdAndSourceId[1];
                if (sourceId == mSourceId) {
                    // 已订阅状态
                    mSubscribeButton.setTextColor(getResources().getColor(R.color.button_gray));
                    mSubscribeButton.setText(R.string.cancel_subscribe);
                    mSubscribeButton.setBackgroundResource(R.drawable.selector_gray_btn);
                    mSource.isSubscribed = true;
                    // 订阅数
                    mSource.subscribeCount++;
                    mSubscribeCountText.setText(getString(R.string.people_has_subscribed,
                            mSource.subscribeCount));
                }
            }
        };

        @Override
        public void onUnsubscribe(int transactionId, int sourceId) {
            if (mSubscribeTid == transactionId) {
                if (sourceId == mSourceId) {
                    // 未订阅状态
                    mSubscribeButton.setTextColor(Color.WHITE);
                    mSubscribeButton.setText(R.string.subscribe);
                    mSubscribeButton.setBackgroundResource(R.drawable.selector_blue_btn);
                    mSource.isSubscribed = false;
                    // 订阅数
                    mSource.subscribeCount--;
                    mSubscribeCountText.setText(getString(R.string.people_has_subscribed,
                            mSource.subscribeCount));
                }
            }
        };

        @Override
        public void onGetSourceInfoList(int transactionId, boolean hasMore, long maxTime) {
            if (mHeadSourceInfoTid == transactionId) {
                // // 接收头条消息
                mSourceInfoTid = XoneService.getInstance().doGetSourceInfoList(
                        String.valueOf(mSourceId), TransactionGetSourceInfoList.TYPE_COMMON,
                        XoneConsts.LIST_ITEM_COUNT.ONE_REQUEST_COUNT, -1);
            } else if (mSourceInfoTid == transactionId) {
                mMaxTime = maxTime;
                mLoadingList.onLoadingComplete(hasMore);
            }
        };

        @Override
        public void onGetSourceInfoListError(int transactionId, int errCode, String err) {
            if (mHeadSourceInfoTid == transactionId) {
                if (errCode == XoneServiceCode.NETWORK_ERR_COMMON) {
                    mLoadingList.onNoNetwork();
                } else {
                    mLoadingList.onLoadingError();
                }
            } else if (mSourceInfoTid == transactionId) {
                mLoadingList.onLoadingComplete(false);
            }
        };
    };

    @Override
    public android.support.v4.content.Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        StringBuilder where = new StringBuilder();
        where.append(AppInfoTable.C_INFOGROUP).append("=")
                .append(ManagerAppInfo.GROUP_SOURCE_INFO_LIST).append(" AND ")
                .append(AppInfoTable.C_SORTTYPE).append("=").append(mSourceId).append(" AND ")
                .append(AppInfoTable.C_ACCOUNT).append("='")
                .append(ManagerAccount.getInstance().getCurrentAccountId()).append("'");
        return new CursorLoader(getActivity(), AppInfoTable.CONTENT_URI, ManagerAppInfo.Projection,
                where.toString(), null, null);
    }

    @Override
    public void onLoadFinished(android.support.v4.content.Loader<Cursor> arg0, Cursor cursor) {
        // Swap the new cursor in. (The framework will take care of closing the
        // old cursor once we return.)
        mAdapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(android.support.v4.content.Loader<Cursor> arg0) {
        // This is called when the last Cursor provided to onLoadFinished()
        // above is about to be closed. We need to make sure we are no
        // longer using it.
        mAdapter.swapCursor(null);
    }

}
